<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 总包签证确认归档编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"
                       @selectOrg="selectOrg"
                       @getProjectInfo="getProjectInfo">
            <template #monitoringContent>
              <a-tree-select  v-model="form.monitoringContent"
                              :disabled= "editModel == 0"
                              show-search
                              treeNodeFilterProp='title'
                             placeholder="请选择"
                             :tree-data="monitoringContentData"
                              :replaceFields="{
                               children:'children',title:'monitoringContentName', key:'id', value: 'id'
                            }"
                             allow-clear
                              treeNodeLabelProp="label"
                              @select="treeSelectChange"
              >
              </a-tree-select>
            </template>
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table businessCode="FACE11" :uploadArrys.sync="form.fileInfoList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileInfoList" style="margin-top: -3px"></file-link>
            </template>
            <template #photo>
              <div v-if="editModel == 0 && (!form.photo || form.photo.length < 1)" style="margin-top: -3px">
                无
              </div>
              <l-table
                v-else
                uploadType="image"
                businessCode="FACE11"
                :disabled="editModel == 0"
                :editModel="editModel"
                :uploadArrys.sync="form.photo"
                multiple
              ></l-table>
              <!-- <div v-if="editModel != 0" class="file_prompt">需上传建筑全景照片</div> -->
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            v-if="form.status == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <!-- <a-button
            v-else
            class="button_right"
            type="primary"
            :loading="loadingBtn.DRAFT"
            @click="handleSubmit('DRAFT')"
            >保存草稿</a-button
          > -->
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
     
  </base-breadcrumb>
</template>

<script>
import {addTechnicalMeasurementMonitoring,updateTechnicalMeasurementMonitoring,getTechnicalMeasurementMonitoringById} from '@/api/technical/measurement' // api
import { getdropDownChoice} from '@/api/technical/monitoringContent'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonByProject from '@/components/Select/SelectPersonByProject' //参与人员
import { monitoringData,conclusionMonitoringData,isAbnormalData} from './model'
import moment from "moment"

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { projectDeptId: void 0, commissionFileInfoList: [], curId: '', projectId: "", branchComId: "" }, // 表单
      monitoringContentData:[], //监测内容下拉框
      isThreeMonitoringContent:false,  //是否为三方监测
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        monitoringMainContent: [{ required: true, message: '请输入监测主要内容', trigger: 'blur' },],
        monitoringUnit: [{ required: true, message: '请输入监测单位', trigger: 'blur' },],
        projectPosition: [{ required: true, message: '请输入工程部位', trigger: 'blur' },],
        monitoringReportName: [{ required: true, message: '请输入监测报告名称', trigger: 'blur' },],
        isAbnormal: [{ required: true, message: '请选择监测是否出现异常或超出预警值', trigger: 'change' }],
        participant: [{ required: true, message: '请选择参与人员', trigger: 'change' }],
        monitoringContent: [{ required: true, message: '请选择监测内容', trigger: 'change' }],
        monitoringTime: [{ required: true, message: '请选择监测时间', trigger: 'change' }],
        monitoringFrequency: [{ required: true, message: '请选择监测频率要求', trigger: 'change' }],
        conclusionMonitoring: [{ required: true, message: '请选择监测结论', trigger: 'change' }],
        fileInfoList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }],
        // photo: [{ type: 'array', required: true, message: '请上传照片', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件
      disabledDateList: [],
      monitoringContentName: ''
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileInfoList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileInfoList')
        })
      }
    },
    // 监听照片实现照片校验
    'form.photo'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('photo')
        })
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    //监听 监测内容
    'form.monitoringContent'(newVal) {
       newVal && this.findIdMonitoringContent(newVal);
    },
  },
  async created() {
     await this.getPageTechnicalMonitoringContentListFn();
  },
  async mounted() {
    this.$route.meta.title = ['测量监测 查看', '测量监测 编辑', '测量监测 新增'][this.editModel]
    await this.getDetailData()
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'curId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: true
        },
        {
          keyName: 'monitoringContent',
          disabled: this.editModel == 0,
          label: '监测内容',
          slot: true,
          data: this.monitoringContentData,
        },
        {
          keyName: 'projectPosition',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '工程部位',
        },
        {
          keyName: 'monitoringUnit',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '监测单位',
          hidden: !this.isThreeMonitoringContent,
         },
         {
          keyName: 'monitoringReportName',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '监测报告名称',
          hidden: !this.isThreeMonitoringContent,
         },
        {
          keyName: 'monitoringTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
           label: '监测时间',
            attrs: {
                valueFormat: 'YYYY-MM-DD'
            }
        },
        {
          keyName: 'participant',
          type: SelectPersonByProject,
          label: '参与人员',
          placeholder: '搜索下拉，可多选',
          hidden: this.isThreeMonitoringContent,
          disabled: this.editModel == 0,
          attrs: {
            isOrg: true,
            showSearch: true,
            orgId: this.form.projectDeptId,
            mode: 'multiple',
            optionLabelProp: 'children'
          }
        },
        {
          keyName: 'monitoringFrequency',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '监测频率要求',
          data: monitoringData,
          hidden: this.isThreeMonitoringContent,
        },
        {
          keyName: 'monitoringMainContent',
          type: 'BaseTextarea',
          disabled: this.editModel == 0,
          label: '监测主要内容',
          span: 24,
          hidden: this.isThreeMonitoringContent,
        },
        {
          keyName: 'conclusionMonitoring',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '监测结论',
          data: conclusionMonitoringData,
          hidden: this.isThreeMonitoringContent,
        },
        {
          keyName: 'modifiedName',
          type: 'BaseInput',
          disabled: true,
          hidden: this.editModel*1 === 2,
          label: '填报人'
        },
         {
          keyName: 'modifiedTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled:true,
          label: '填报时间',
          hidden: this.editModel*1 === 2,
            attrs: {
                valueFormat: 'YYYY-MM-DD'
            }
        },
        {
          keyName: 'isAbnormal',
          type: 'a-radio-group',
          disabled: this.editModel == 0,
          label: '监测是否出现异常或超出预警值',
          data: isAbnormalData,
          hidden: !this.isThreeMonitoringContent,
        },
        {
          slot: true,
          keyName: 'fileInfoList',
          label: '附件上传',
          span: 24,
          businessCode: 'FACE11'
        },{
          slot: true,
          keyName: 'photo',
          label: '上传照片',
          span: 24,
          businessCode: 'FACE11',
          hidden: this.isThreeMonitoringContent,
        },
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val.length&&val.length < 2) {
        this.form.branchComId = val[val.length - 1].orgId
      } else if(val.length >= 2 ) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.projectId = val[val.length - 1].projectId
      }
    },
    getProjectInfo(info) {
      this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
    },
    //获取监测内容数据
   async getPageTechnicalMonitoringContentListFn(){
      let req= await getdropDownChoice({});
      if(req.code=='0'){
        req.data.forEach((item) => {
          item.label = item.monitoringContentName
          if(item.status == 1) {
            item.disabled = true
          }
          if(item.monitoringContentName === '第三方监测报告') {
            item.isThree = 1
          } else {
            item.isThree = 0
          }
          if(item.children&&item.children.length) {
            item.selectable = false
            item.children.forEach(ele=>{
              if(ele.status == 1) {
                ele.disabled = true
              }
              if(item.monitoringContentName === '第三方监测报告') {
                ele.isThree = 1
              } else {
                ele.isThree = 0
              }
              ele.label = item.monitoringContentName + '-' + ele.monitoringContentName
            })
          }
        })
        this.monitoringContentData = req.data;
      }
    },
    treeSelectChange(value, node) {
      this.monitoringContentName = node.dataRef.label
      this.isThreeMonitoringContent = node.dataRef.isThree === 1
      this.$set(this.form, 'monitoringMainContent', null)
      this.$set(this.form, 'monitoringUnit', null)
      this.$set(this.form, 'projectPosition', null)
      this.$set(this.form, 'monitoringReportName', null)
      this.$set(this.form, 'isAbnormal', null)
      this.$set(this.form, 'monitoringTime', null)
      this.$set(this.form, 'participant', [])
      this.$set(this.form, 'participantName', null)
      this.$set(this.form, 'conclusionMonitoringName', null)
      this.$set(this.form, 'monitoringFrequency', null)
      this.$set(this.form, 'monitoringFrequencyName', null)
      this.$set(this.form, 'conclusionMonitoring', null)

    },
    findIdMonitoringContent(id){
      // if(id && this.monitoringContentData.length){
      //    let findData = this.monitoringContentData.find(item=>item.id*1 === id*1)
      //    this.isThreeMonitoringContent = findData.isThree !== 1
      // }
    },
      filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
      return flag
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getTechnicalMeasurementMonitoringById({ id: this.id })
          .then((res) => {
            this.loading = false
            if(res.data.participant){
              res.data.participant = res.data.participant.split(',');
            } else {
              res.data.participant = []
            }
            if(res.data.monitoringContent){
              this.isThreeMonitoringContent = res.data.monitoringContentName.indexOf('第三方监测报告') > -1 ? true:false
              this.monitoringContentName = res.data.monitoringContentName
            //   let monitoringContentArr = {
            //     isThree:1,
            //     label:res.data.monitoringContentName,
            //     value:res.data.monitoringContent
            //   };
            //   // 如果监测内容被删除了，就是添加
            //   let isMonitoringContent = this.monitoringContentData.find((item)=>item.value*1===res.data.monitoringContent*1);
            //   !isMonitoringContent && this.monitoringContentData.push(monitoringContentArr);
            }
            if(this.editModel == 1) {
              res.data.modifiedTime = moment().format("YYYY-MM-DD")
              res.data.modifiedName = this.$userInfo().name
            }
            this.form = { ...this.form, ...res.data }
            if(this.form.projectId) {
              this.form.curId =  this.form.projectId
            } else {
              this.form.curId =  this.form.branchComId
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.form.curId = this.$userInfo().currentPost.id
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      let form = this.$clone(this.form)
      if(form.participant?.length){
          form.participant = this.form.participant.join(',');
      } else {
        form.participant = null
      }
      let api = [updateTechnicalMeasurementMonitoring, addTechnicalMeasurementMonitoring][this.editModel - 1]
      form.monitoringContentName = this.monitoringContentName
      api(form)
        .then(() => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
